<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="btn-add">
        <el-button
        icon="el-icon-circle-plus-outline"
        type="button"
        class="el-button el-button--primary"
        @click="showAdd = true"
        >
            新增</el-button
        >
    </div>

    <!-- 新增数据弹窗 -->
    <el-dialog
      title="新增物料编码长度"
      :visible.sync="showAdd"
      @close="showAdd = false"
      width="35%"
    >
        <el-form :model="createForm" ref="createForm" :rules="addRules" label-width="80px">
            <el-form-item label="子件编码" prop="materialCode" >
                <el-input v-model.trim="createForm.materialCode" class="ul-item" />
            </el-form-item>
            <el-form-item label="机柜条码" prop="deviceBarcode" >
                <el-input v-model.trim="createForm.deviceBarcode" class="ul-item" />
            </el-form-item>
            <el-form-item label="器件条码" prop="deviceCode" >
                <el-input @input="Codechange" v-model.trim="createForm.deviceCode" class="ul-item" />
            </el-form-item>
            <el-form-item label="编码长度" prop="len" >
                <el-input disabled v-model.number="createForm.len" class="ul-item" />
            </el-form-item>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addplate('createForm')">新增</el-button>
        </div>
    </el-dialog>

    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->
        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.texture) }"
            v-model.trim="param.materialCode"
            placeholder="子件编码"
        ></el-input>

        <!-- <el-input
            @keyup.enter.native="getData"
            clearable
            style="width: 150px;margin-right:15px;"
            v-model.number="param.len"
            placeholder="编码长度"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="width: 150px;margin-right:15px;"
            v-model.trim="param.deviceBarcode"
            placeholder="机柜条码"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="width: 150px;margin-right:15px;"
            v-model.trim="param.deviceCode"
            placeholder="器件条码"
        ></el-input> -->

        <el-select
              v-model="param.isDelete"
              placeholder="状态"
              style="width: 150px;margin-right:15px;margin-top:7px">
              <el-option
              :value="item"
              :label="item"
              v-for="(item,index) of this.statusList"
              :key="index"/>
          </el-select>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>
    
    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="子件编码"  prop="materialCode" align="center"/>
      <el-table-column label="编码长度"  prop="len" align="center"/>
      <el-table-column label="对标的机柜条码"  prop="deviceBarcode" align="center"/>
      <el-table-column label="对标的器件条码"  prop="deviceCode" align="center"/>
      <el-table-column label="添加姓名"  prop="userName" align="center"/>
      <el-table-column label="修改时间"  prop="updateTime" align="center"/>
      <el-table-column label="操作" fixed="right" align="center" width="160">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <!-- <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button> -->
                    <el-button
                        icon="el-icon-delete"
                        class="el-button el-button--danger"
                        style="font-size: 15px;"
                        @click="handleDelete(scope.row,scope.$index)"
                    ></el-button>
                </div>
            </template>
      </el-table-column>
    </el-table>

    <!-- 修改数据弹窗 -->
    <el-dialog
      title="修改物料编码长度"
      :visible.sync="showupd"
      @close="showupd = false"
      width="35%"
    >
        <el-form :model="updForm" ref="updForm" :rules="addRules" label-width="80px">
            <el-form-item label="子件编码" prop="materialCode" >
                <el-input v-model.trim="updForm.materialCode" class="ul-item" />
            </el-form-item>
            <el-form-item label="机柜条码" prop="deviceBarcode" >
                <el-input v-model.trim="updForm.deviceBarcode" class="ul-item" />
            </el-form-item>
            <el-form-item label="器件条码" prop="deviceCode" >
                <el-input v-model.trim="updForm.deviceCode" class="ul-item" />
            </el-form-item>
            <el-form-item label="编码长度" prop="len" >
                <el-input disabled v-model.number="updForm.len" class="ul-item" />
            </el-form-item>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showupd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="updprocess('updForm')">修改</el-button
            >
        </div>
    </el-dialog>
   
   <!-- pagination 分页 -->
    <!-- <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div> -->

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { historyLenth,historyLenthins,updplate,historyLenthdel } from "@/api/processRoute"
import { getCenter } from '../../api/workSection.js'
export default {
    name: 'emsScanningMaterial',
    data () {
        return {
            listQuery: {
                // page: 1,                                    //页码
                // limit: 10                                   //每页多少条记录
            },
            param: {
                materialCode:'',
                isDelete: '未删除',
            },
            total: 0,                                      //数据的总数
            tableInfo: [],
            loadingList: false,
            loading: false,
            createForm: {},
            updForm: {},
            statusList: ['未删除','已删除'],
            // 表单校验
            addRules: {
                materialCode: [
                    { required: true, message: "编码不能为空", trigger: "change" },
                ],
                len: [
                    { required: true, message: "编码长度不能为空", trigger: "change" },
                ],
                deviceBarcode: [
                    { required: true, message: "机柜条码不能为空", trigger: "change" },
                ],
                deviceCode: [
                    { required: true, message: "器件条码不能为空", trigger: "change" },
                ]
            },
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        // 器件条码改变
        Codechange(e){
            this.createForm.len = e.length
        },
        getData(){
        //   this.listQuery.page = 1
        //   this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.len){ query.len = this.param.len}
            if(this.param.materialCode){ query.materialCode = this.param.materialCode}
            if(this.param.deviceBarcode){ query.deviceBarcode = this.param.deviceBarcode}
            if(this.param.deviceCode){ query.deviceCode = this.param.deviceCode}
            this.param.isDelete == '未删除' ? query.isDelete = 0 : query.isDelete = 1
            let data = await historyLenth(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code != '1') return this.$message.error(errmsg)
            // this.total = data.data.total
            this.tableInfo = data.data
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            materialCode: '子件条码',
            len: '编码长度',
            deviceBarcode: '对标机柜条码',
            deviceCode: '对标器件条码'
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          if(this.param.len){ query.len = this.param.len}
          if(this.param.materialCode){ query.materialCode = this.param.materialCode}
          if(this.param.deviceBarcode){ query.deviceBarcode = this.param.deviceBarcode}
          if(this.param.deviceCode){ query.deviceCode = this.param.deviceCode}
          this.param.isDelete == '未删除' ? query.isDelete = 0 : query.isDelete = 1
          let arr = await historyLenth(query)
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          const { header, data } = this.transformDat(this.setSort(arr.data))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '物料编码长度列表', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              materialCode:item.materialCode,
              len:item.len,
              deviceBarcode:item.deviceBarcode,
              deviceCode:item.deviceCode,
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {}
            // this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addplate(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                        this.submitplate()
                } else {
                    return false
                }
            })
        },
        async submitplate(){
            if(this.createForm.deviceCode.length != this.createForm.len) return this.$message.error('器件条码长度和设置的编码长度不符！')
            let query = Object.assign({},this.createForm)
            if(query.deviceBarcode.includes('06S') && query.deviceBarcode.includes('1P')){
				query.deviceBarcode = query.deviceBarcode.match(/06S(\S*)1P/)[1]
			}
            if(query.deviceCode.includes('06S') && query.deviceCode.includes('1P')){
				query.deviceCode = query.deviceCode.match(/06S(\S*)1P/)[1]
			}
            const data = await historyLenthins(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.resetForm()
            this.showAdd = false
            this.handleFilter()
        },
        resetForm(){
             this.$refs.createForm.resetFields();
        },
        handleEdit(row){
            this.updForm = Object.assign({},row)
            this.showupd = true
        },
        // 提交表单之前先进行验证
        updprocess(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.updplate()
                } else {
                    return false
                }
            })
        },
        async updplate(){
            let query = Object.assign({},this.updForm)
            const data = await historyLenthins(query)
            const errMsg = data.msg
            if(data.code != '1') return this.$message.error(errMsg)
            this.showupd = false
            this.handleFilter()
            this.$message.success(errMsg)
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delprocess(row,index)
            }).catch(() => {
                this.$message({
                  type: 'info', 
                  message: '已取消删除'
                })
            })
        },
        async delprocess(row,index){
          let res = await historyLenthdel({id: row.id})
          if(res.code != '1') return this.$message.error(res.msg)
          this.handleFilter()
          this.$message.success(res.msg)
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>